import { createWebHistory, createRouter } from 'vue-router'
import MainLayout from '@/components/Layout/MainLayout.vue';
import AdminDashboard from '@/components/Admin/Dashboard.vue';
import useAuthStore from '@/stores/auth'
import { ElMessage } from 'element-plus';
import component from 'element-plus/es/components/tree-select/src/tree-select-option.mjs';

// 白名单路由
const whiteList = ['/login', '/register', '/forgot-password']

const routes = [
    {
      path: '/login',
      name: 'Login',
      component: () => import('@/views/Authority/Login.vue')
    },
    {
      path: '/register',
      name: 'Register',
      component: () => import('@/views/Authority/Register.vue')
    },
    // 普通用户路由

    {
      path: '/',
      redirect: '/index',
      component: MainLayout,
      name: 'Index',
      children:[
        
        {
          path:'index',
          name:'index',
          component:()=>import('@/components/Layout/index.vue')
        }
      ]
    },
    // 超级管理员路由
    {
      path: '/admin',
      name: 'Admin',
      component: MainLayout,
      redirect: '/admin/users',
      children: [
        {
          path: 'users',
          name: 'UserManagement',
          component: () => import('@/views/admin/UserManagement.vue'),
          meta: { requiresAuth: true, requiresAdmin: true }
        },
        {
          path: 'logs',
          name: 'OperationLog',
          component: () => import('@/views/admin/OperationLog.vue'),
          meta: { requiresAuth: true, requiresAdmin: true }
        }
      ]
    },
    {
      path:'/userManage',
      name:'userManage',
      component:()=>import('@/views/Common/userManage/index.vue'),
      meta: { requiresAuth: true }
    }
]

const router = createRouter({
  history: createWebHistory(),
  routes,
})

router.beforeEach(async (to, from, next) => {
  const authStore = useAuthStore()
  // 设置页面标题
  document.title = to.meta.title ? `${to.meta.title} - 社团管理系统` : '社团管理系统'

  // 白名单路由直接放行
  if (whiteList.includes(to.path)) {
    next()
    return
  }

  // 检查登录状态
  if (!authStore.isAuthenticated) {
    ElMessage.error("未登录")
    next({
      path: '/login',
      query: { redirect: to.fullPath }
    })
    return
  }

  // 已登录用户访问登录页，重定向到首页
  if (to.path === '/login') {
    next({ path: '/' })
    return
  }

  // 管理员权限验证
  if (to.path.startsWith('/admin')) {
    if (authStore.userInfo?.userAccount !== 'admin') {
      console.log(authStore.userInfo)
      ElMessage.error("无权限访问")
      next('/')
      return
    }
  }

  next()
})

// 路由错误处理
router.onError((error) => {
  console.error('路由错误:', error)
})

export default router;